<template>
  <div class="image-loader-container">
    <img v-if="!everythingDone" class="placeholder" :src="placeholder" alt="">
    <img @load="handleLoad" :src="src" alt="" :style="{opacity: loadOverOpacity, transition: `all ${duration}ms`}">
  </div>
</template>

<script>
export default {
  name: 'ImageLoader',
  props: {
    src: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      required: true
    },
    duration: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      isLoadOver: false,  // 原图是否加载完
      everythingDone: false // 是否全部加载完毕
    }
  },
  computed: {
    loadOverOpacity() {
      return this.isLoadOver ? 1 : 0
    }
  },
  methods: {
    handleLoad() {
      this.isLoadOver = true
      setTimeout(() => {
        this.everythingDone = true
        this.$emit('load')
      }, this.duration)
    }
  }
}
</script>
<style scoped lang="less">
@import "~@/styles/mixin.less";
.image-loader-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  img {
    .self-fill();
    object-fit: cover;
  }
  .placeholder {
    filter: blur(2vw);
  }
}
</style>
